using SimpleJSON;
using UnityEngine;
using UnityEngine.UI;

namespace Gj
{
    public class MultipleItemHelper : NodeHelper
    {
        public NodeHelper show;
        public NodeHelper hide;
        public bool button;
        public bool fix;
        public AudioClip clip;
        public SoundType soundType;
        public UIEvent uiEvent;

        [SelectRef(UIKey.DATA_KEY)] public SelectKey disabledKey;
        public bool invert;
        private Button _Button;

        protected Button Button
        {
            get
            {
                if (_Button == null) _Button = UnityTools.GetComponentRequire<Button>(gameObject);
                return _Button;
            }
        }

        protected override void Start()
        {
            if (button && Button != null) Button.onClick.AddListener(BindClick);
        }

        public override void SetData(JSONObject json)
        {
            base.SetData(json);
            if (button && Button != null && !disabledKey.IsEmpty())
                Button.interactable = invert ? disabledKey.Get(json).AsBool : !disabledKey.Get(json).AsBool;
        }

        private void BindClick()
        {
            if (uiEvent != UIEvent.None)
                Emit(uiEvent);
            else
                Click();

            if (soundType != SoundType.None)
                Game.single.PlayEFF(soundType);
            else if (clip != null) Game.single.PlayEFF(clip);
        }

        protected override void Init()
        {
            if (show != null && hide != null)
            {
                child.Add(show);
                child.Add(hide);
            }

            base.Init();
        }

        protected override void BindData(bool b)
        {
            if (show != null && hide != null)
            {
                if (b)
                {
                    show.gameObject.SetActive(b);
                    hide.gameObject.SetActive(!b);
                }
                else
                {
                    hide.gameObject.SetActive(!b);
                    show.gameObject.SetActive(b);
                }
            }
            else
            {
                if (!fix) gameObject.SetActive(b);
            }
        }
    }
}